//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react';
import { Button, List, message, Modal, Popover, Select, Space, Table, Tabs } from 'antd';
import { useStores } from '@/hooks';
import { CloseOutlined, CopyOutlined, LinkOutlined, MoreOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons';
import moment from 'moment';
import { open as shell_open } from '@tauri-apps/api/shell';
import { USER_TYPE_ATOM_GIT, USER_TYPE_GITEE } from '@/api/user';
import type { MailAccount, MailInfo } from "@/api/user_mail";
import {
    list_account as list_mail_account, create_account as create_mail_account, update_account as update_mail_account, remove_account as remove_mail_account,
    list_mail, set_mail_state, remove_mail,
} from "@/api/user_mail";
import { request } from '@/utils/request';
import { EditText } from '../EditCell/EditText';
import { writeText } from '@tauri-apps/api/clipboard';
import type { ColumnsType } from 'antd/lib/table';
import { appWindow, WebviewWindow } from '@tauri-apps/api/window';
import { uniqId } from '@/utils/utils';
import { listen } from '@tauri-apps/api/event';
import type * as NoticeType from '@/api/notice_type';

const PAGE_SIZE = 20;

const GitNoticeList = observer(() => {
    const userStore = useStores('userStore');

    return (
        <List rowKey="id" dataSource={userStore.gitNoticeList} pagination={false} style={{ height: "calc(100vh - 300px)", overflowY: "scroll", padding: "0px 10px" }}
            renderItem={noticeItem => (
                <List.Item>
                    <div>
                        <div>{moment(noticeItem.updated_at).format("YYYY-MM-DD HH:mm")}</div>
                        <a style={{ fontSize: "14px" }} onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            shell_open(noticeItem.html_url);
                        }}>{noticeItem.content}</a>
                    </div>
                </List.Item>
            )} />
    );
});

interface MailListProps {
    version: number;
    listType: "all" | "unread";
}

const MailList = observer((props: MailListProps) => {
    const userStore = useStores("userStore");
    const appStore = useStores('appStore');

    const [mailList, setMailList] = useState<MailInfo[]>([]);
    const [totalCount, setTotalCount] = useState(0);
    const [curPage, setCurPage] = useState(0);

    const loadMailList = async () => {
        console.log(props.listType == "unread", props.listType == "all");
        const res = await list_mail({
            session_id: userStore.sessionId,
            filter_by_has_read: props.listType == "unread",
            has_read: props.listType == "all",
            offset: curPage * PAGE_SIZE,
            limit: PAGE_SIZE,
        });
        setTotalCount(res.total_count);
        setMailList(res.info_list);
    };

    const markMailHasRead = async (mailId: string, hasRead: boolean) => {
        await request(set_mail_state({
            session_id: userStore.sessionId,
            mail_id: mailId,
            has_read: hasRead,
        }));
        await userStore.loadUserMailStatus();
        const tmpList = mailList.slice();
        const index = tmpList.findIndex(item => item.mail_id == mailId);
        if (index != -1) {
            tmpList[index].has_read = hasRead;
            setMailList(tmpList);
        }
    };

    const removeMail = async (mailId: string) => {
        await request(remove_mail({
            session_id: userStore.sessionId,
            mail_id: mailId,
        }));
        await loadMailList();
        await userStore.loadUserMailStatus();
        message.info("删除成功");
    };

    const openWindow = async (mailId: string) => {
        const label = `usermail:${uniqId().replaceAll("-", "")}`;
        const view = WebviewWindow.getByLabel(label);
        if (view != null) {
            await view.close();
        }
        const pos = await appWindow.innerPosition();
        new WebviewWindow(label, {
            url: `user_mail.html?id=${encodeURIComponent(mailId)}`,
            x: pos.x + Math.floor(Math.random() * 500),
            y: pos.y + Math.floor(Math.random() * 200),
            width: 500,
            height: 400,
            decorations: false,
            alwaysOnTop: true,
            skipTaskbar: true,
            fileDropEnabled: false,
            resizable: true,
        });
    };

    const columns: ColumnsType<MailInfo> = [
        {
            title: "标题",
            width: 100,
            render: (_, row: MailInfo) => (
                <a style={{ fontWeight: row.has_read ? 100 : 700, color: row.has_read ? "grey" : "blue" }}
                    onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        openWindow(row.mail_id);
                    }}>{row.title}</a>
            ),
        },
        {
            title: "发件人",
            width: 80,
            ellipsis: true,
            dataIndex: "from_account",
        },
        {
            title: "发送时间",
            width: 80,
            render: (_, row: MailInfo) => moment(row.time_stamp).format("YYYY-MM-DD HH:mm"),
        },
        {
            title: "操作",
            width: 70,
            render: (_, row: MailInfo) => (
                <Space>
                    {row.has_read == true && (<Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            markMailHasRead(row.mail_id, false);
                        }}>标记为未读</Button>)}
                    {row.has_read == false && (<Button type="link" style={{ minWidth: "0px", padding: "0px 0px" }}
                        onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            markMailHasRead(row.mail_id, true);
                        }}>标记为已读</Button>)}
                    <Popover placement='bottom' trigger="click" content={
                        <Space>
                            <Button type="link" danger onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                removeMail(row.mail_id);
                            }}>删除</Button>
                        </Space>
                    }>
                        <MoreOutlined />
                    </Popover>
                </Space>
            ),
        }
    ];

    useEffect(() => {
        if (curPage != 0) {
            setCurPage(0);
            return;
        }
        loadMailList();
    }, [props.version, props.listType]);

    useEffect(() => {
        loadMailList();
    }, [curPage]);


    useEffect(() => {
        const unListenFn = listen<NoticeType.AllNotice>("notice", ev => {
            const notice = ev.payload;
            if (notice.ClientNotice?.RemoveMailNotice !== undefined) {
                loadMailList();
            } else if (notice.ClientNotice?.UpdateMailStateNotice !== undefined) {
                loadMailList();
            }
        });
        return () => {
            unListenFn.then((unListen) => unListen());
        };
    }, [props.listType]);

    return (
        <Table rowKey="mail_id" dataSource={mailList} columns={columns} scroll={{ y: "calc(100vh - 300px)" }}
            pagination={{ total: totalCount, current: curPage + 1, pageSize: PAGE_SIZE, onChange: page => setCurPage(page - 1), showTotal: () => `只保存最近${appStore.clientCfg?.max_mail_count_per_user}封邮件` }} />
    );
});

interface ConfigPanelProps {
    version: number;
    onAccountCount: (newCount: number) => void;
}

const ConfigPanel = observer((props: ConfigPanelProps) => {
    const userStore = useStores("userStore");
    const appStore = useStores("appStore");

    const [mailAccountList, setMailAccountList] = useState<MailAccount[]>([]);

    const loadMailAccountList = async () => {
        const res = await request(list_mail_account({
            session_id: userStore.sessionId,
        }));
        setMailAccountList(res.account_list);
        props.onAccountCount(res.account_list.length);
    };

    useEffect(() => {
        loadMailAccountList();
    }, [props.version]);

    return (
        <List rowKey="account" dataSource={mailAccountList} pagination={false} style={{ height: "calc(100vh - 300px)", overflowY: "scroll", padding: "0px 10px" }}
            renderItem={item => (
                <List.Item extra={
                    <Space>
                        <Button type="text" icon={<CopyOutlined />} title='复制账号' onClick={e => {
                            e.stopPropagation();
                            e.preventDefault();
                            writeText(`${item.account}@${appStore.clientCfg?.user_mail_domain}`);
                            message.info("复制成功");
                        }} />
                        <Popover placement='bottom' trigger="click" content={
                            <Space direction='vertical'>
                                <Button type="link" danger onClick={e => {
                                    e.stopPropagation();
                                    e.preventDefault();
                                    request(remove_mail_account({
                                        session_id: userStore.sessionId,
                                        account: item.account,
                                    })).then(() => {
                                        loadMailAccountList();
                                        message.info("删除成功");
                                    });
                                }}>删除</Button>
                            </Space>
                        }>
                            <MoreOutlined />
                        </Popover>
                    </Space>
                }>
                    <Space>
                        <span>{item.account}@{appStore.clientCfg?.user_mail_domain}</span>
                        <span>备注:
                            <EditText editable content={item.remark} showEditIcon
                                onChange={async value => {
                                    try {
                                        await request(update_mail_account({
                                            session_id: userStore.sessionId,
                                            account: item.account,
                                            remark: value.trim(),
                                        }));
                                        await loadMailAccountList();
                                        return true;
                                    } catch (e) {
                                        console.log(e);
                                        return false;
                                    }
                                }} />
                        </span>
                    </Space>
                </List.Item>
            )} />
    );
});

export interface NoticeModalProps {
    onClose: () => void;
}

const NoticeModal = (props: NoticeModalProps) => {
    const userStore = useStores('userStore');
    const appStore = useStores('appStore');

    const [activeKey, setActiveKey] = useState("");
    const [mailListVersion, setMailListVersion] = useState(0);
    const [mailCfgVersion, setMailCfgVersion] = useState(0);
    const [mailAccountCount, setMailAccountCount] = useState(0);

    const [listMailType, setListMailType] = useState<"all" | "unread">("unread");

    useEffect(() => {
        if (activeKey != "") {
            return;
        }
        if ([USER_TYPE_ATOM_GIT, USER_TYPE_GITEE].includes(userStore.userInfo.userType)) {
            setActiveKey("git");
        } else if (appStore.vendorCfg?.ability.enable_user_mail && appStore.clientCfg?.enable_user_mail) {
            setActiveKey("mail");
        }
    }, [appStore.clientCfg, appStore.vendorCfg]);

    return (
        <Modal open footer={null} mask={false} closable={false}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }} bodyStyle={{ padding: "0px 0px" }}>
            <Tabs type="card"
                activeKey={activeKey}
                onChange={key => setActiveKey(key)}
                tabBarExtraContent={
                    <Space size="small">
                        {activeKey == "git" && (
                            <>
                                <Button type="link" icon={<LinkOutlined />} style={{ minWidth: "0px", padding: "0px 0px" }}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        if (userStore.userInfo.userType == USER_TYPE_ATOM_GIT) {
                                            shell_open("https://atomgit.com/-/profile/notice/infos");
                                        } else if (userStore.userInfo.userType == USER_TYPE_GITEE) {
                                            shell_open("https://gitee.com/notifications/infos");
                                        }
                                    }}>网页查看</Button>
                                <Button type="link" icon={<ReloadOutlined />} title='刷新' style={{ minWidth: "0px", padding: "0px 0px" }}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        userStore.loadGitNoticeList().then(() => message.info("刷新成功"));
                                    }} />
                            </>
                        )}
                        {activeKey == "mail" && (
                            <>
                                <Select value={listMailType} onChange={value => setListMailType(value)} style={{ width: "60px" }}>
                                    <Select.Option value="all">全部</Select.Option>
                                    <Select.Option value="unread">未读</Select.Option>
                                </Select>
                                <Button type="link" icon={<ReloadOutlined />} title='刷新' style={{ minWidth: "0px", padding: "0px 0px" }}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setMailListVersion(mailListVersion + 1);
                                        message.info("刷新成功");
                                    }} />
                            </>
                        )}
                        {activeKey == "config" && (
                            <>
                                <Button type="primary" size='small' icon={<PlusOutlined />} disabled={mailAccountCount >= (appStore.clientCfg?.max_mail_account_per_user ?? 0)}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        request(create_mail_account({
                                            session_id: userStore.sessionId,
                                        })).then(() => {
                                            setMailCfgVersion(mailCfgVersion + 1);
                                            message.info("创建成功");
                                        });
                                    }}>创建账号</Button>
                                <Button type="link" icon={<ReloadOutlined />} title='刷新' style={{ minWidth: "0px", padding: "0px 0px" }}
                                    onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setMailCfgVersion(mailCfgVersion + 1);
                                        message.info("刷新成功");
                                    }} />
                            </>
                        )}
                        <Button type="link" icon={<CloseOutlined />} title='关闭' style={{ minWidth: "0px", padding: "0px 0px" }}
                            onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                props.onClose();
                            }} />
                    </Space>
                }>
                {[USER_TYPE_ATOM_GIT, USER_TYPE_GITEE].includes(userStore.userInfo.userType) && (
                    <Tabs.TabPane key="git" tab={<span style={{ fontSize: "16px", fontWeight: 600 }}>Git通知</span>}>
                        {activeKey == "git" && <GitNoticeList />}
                    </Tabs.TabPane>
                )}
                {appStore.vendorCfg?.ability.enable_user_mail && appStore.clientCfg?.enable_user_mail && (
                    <>
                        <Tabs.TabPane key="mail" tab={<span style={{ fontSize: "16px", fontWeight: 600 }}>邮件通知</span>}>
                            {activeKey == "mail" && <MailList version={mailListVersion} listType={listMailType} />}
                        </Tabs.TabPane>
                        <Tabs.TabPane key="config" tab={<span style={{ fontSize: "16px", fontWeight: 600 }}>邮件配置</span>}>
                            {activeKey == "config" && <ConfigPanel version={mailCfgVersion} onAccountCount={newCount => setMailAccountCount(newCount)} />}
                        </Tabs.TabPane>
                    </>
                )}
            </Tabs>
        </Modal>
    );
};

export default observer(NoticeModal);